package com.slz3.business.module.systemManagement.sysUser.service;

import com.slz3.business.frame.module.Repositorys;
import com.slz3.business.frame.util.Md5Utils;
import com.slz3.business.frame.util.UUIDUtils;
import com.slz3.business.module.systemManagement.sysMenu.domain.SysMenuFactory;
import com.slz3.business.module.systemManagement.sysRoleUser.domain.SysRoleUser;
import com.slz3.business.module.systemManagement.sysUser.domain.SysUser;
import com.slz3.business.module.systemManagement.sysUser.domain.SysUserFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.UnknownFormatConversionException;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysUserTransactionalServiceImpl implements SysUserTransactionalService {

    public SysUser modify(SysUser sysUserNew) {
        SysUser sysUser = Repositorys.sysUser.saveAndFlush(sysUserNew);
        Repositorys.sysRoleUser.deleteSysRoleUserByUserUuid(sysUser.getUuid());
        saveRoleUser(sysUserNew);
        return sysUser;
    }

    @Override
    public List<SysUser> batchModify(List<SysUser> sysUserList) {
        return Repositorys.sysUser.saveAll(sysUserList);
    }

    @Override
    public SysUser save(SysUser sysUser) {
        SysUser save = Repositorys.sysUser.save(SysUserFactory.initBaseFields(sysUser));
        saveRoleUser(save);
        return save;
    }

    @Override
    public SysUser login(String serName, String serPass) {
        SysUser sysUser = Repositorys.sysUser.queryFirstBySerName(serName);
        if (serName == null){
            return null;
        }
        String encodePass = Md5Utils.encode(String.format("%s%s", serPass, sysUser.getSaltUuid()));
        if (encodePass.equals(sysUser.getSerPass())){
            return sysUser;
        }
        return null;
    }

    private void saveRoleUser(SysUser sysUser) {
        if (CollectionUtils.isEmpty(sysUser.getRoleUuids())){
            return;
        }
        List<SysRoleUser> collect = sysUser.getRoleUuids().stream().map(item -> {
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUuid(UUIDUtils.generateUUID());
            sysRoleUser.setUserUuid(sysUser.getUuid());
            sysRoleUser.setRoleUuid(item);
            return sysRoleUser;
        }).collect(Collectors.toList());
        Repositorys.sysRoleUser.saveAll(collect);
    }
}
